//
//  BloodOxygenModel.swift
//  MYModule
//
//  Created by 尹琼 on 2022/11/15.
//

import UIKit
import SQLite
import HandyJSON
import MYModule
import SwiftDate

/// 实时血氧
open class BloodOxygenModel: NSObject, MYSQLiteTableiabe, FullDaySQLite, HandyJSON {
    
    public var adress: String = ""
    
    public var id: Int64 = 0
    
    public var date: Date = Date().sqlDate()
    
    public var o2s: [Int] = []
    
    /// 上一次更新数据时间戳
    public var updateTime: Double = 0
    
    
    public required override init() {}
    
    
    public var avg: Int {
        
        var avg = 0
        let o2s = o2s.filter { $0 > 0 && $0 < 255 }
        if o2s.isEmpty {
            return 0
        }
        avg = o2s.reduce(0, { $0 + $1 })/o2s.count
        return avg
       
    }
    
    public var isEmpty: Bool {
        
        return self.o2s.filter { $0 > 0 }.isEmpty
    }
    
    /// 多少分钟一个血氧
    public var aO2Minute: Int {
        
        // 计算出多少分钟一个心率数据
        if o2s.isEmpty {
            return 0
        }
        let aminute = (24 * 60)/o2s.count
        return aminute
    }
    
    
    /// 每一个实时血氧对应的分钟数
    public var allO2Minutes: [Int] {
        
        return (0 ..< self.o2s.count).map { $0 * aO2Minute }
        
    }
    
    
    public func updateData() {
        
        guard let _ = BloodOxygenModel.day(date: date) else {
            insert()
            return
        }
        
        update()
        
    }

    
}
